﻿using SuperX.Common.Log;
using System;
using System.IO;
using SuperX.Common.Object;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;

namespace SuperX.WebAppService
{
    public class WebAppHost
    {
        private IWebHost server;
        public WebAppConfig Config;

        public IDisposable Host;

        public WebAppHost(WebAppConfig config)
        {
            Config = config;
            Init();
        }

        public void Init()
        {
            try
            {
                server = WebHost.CreateDefaultBuilder()
                    .UseUrls($"http://*:{Config.ListeningAddress.Port}")
                    .UseStartup<WebHostCore>()
                    .Build();
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex);
            }
        }

        public void Start()
        {
            try
            {
                Logger.Info("正在启动WebAPP服务 ... ");
                server.StartAsync();
                Logger.Info("WebAPP服务正在运行 ... @ " + $"http://*:{Config.ListeningAddress.Port}");
            }
            catch (Exception ex)
            {
                Logger.Error($"WebAPP服务启动失败！请检查 {Config.ListeningAddress.Port} 端口是否被占用！");
                Logger.ErrorException(ex);
            }
        }

        public void Stop()
        {
            Host?.Dispose();
        }
    }

    public class WebHostCore
    {
        public WebHostCore(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
            //defaultFilesOptions.DefaultFileNames.Clear();
            //defaultFilesOptions.DefaultFileNames.Add("index.html");
            //app.UseDefaultFiles(defaultFilesOptions);
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.GetFullPath(@"Web"))
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Default",
                    template: "",
                    defaults: new { controller = "API", action = "Index" }
                );
            });

            //app.UseMvc();
        }
    }

    public class APIController : BaseController
    {
        public RedirectResult Index()
        {
            return Redirect("/index.html");
        }
    }
}